//
//  MyCommentsViewController.m
//  suRead
//
//  Created by colin on 2020/1/7.
//  Copyright © 2020 bao. All rights reserved.
//

#import "MyCommentsViewController.h"
#import "Masonry.h"
#import "UIControl+Blocks.h"
#import "UIViewController+HUD.h"
#import "ServiceUserNew.h"
#import "NewCellManager.h"
#import <MJRefresh/MJRefresh.h>

@interface MyCommentsViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *infoTableView;
@property(nonatomic,strong)NSMutableArray<M_News *> *news;
@property(nonatomic,assign)NSInteger pageIndex;
@property(nonatomic,assign)NSInteger pageSize;
@property(nonatomic,strong)NSURLSessionTask *requestHandle;
@end

@implementation MyCommentsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageSize = 20;
    self.news = [NSMutableArray array];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *topBar = [UIView new];
    topBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topBar];
    [topBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        if (iPhoneX) {
            make.top.equalTo(topBar.superview).offset(44.0f);
        } else {
            make.top.equalTo(topBar.superview).offset(20.0f);
        }
        make.height.equalTo(@44.0f);
    }];
    
    __weak typeof(self) weakSelf = self;
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonBack setImage:[UIImage imageNamed:@"button_backward"] forState:UIControlStateNormal];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        //返回
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    [topBar addSubview:buttonBack];
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(buttonBack.superview);
        make.centerY.equalTo(buttonBack.superview);
        make.width.equalTo(@44.0f);
        make.height.equalTo(@44.0f);
    }];
    
    UILabel *labelTitle = [UILabel new];
    labelTitle.textColor = [UIColor blackColor];
    labelTitle.text = @"我的评论";
    labelTitle.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:17.0f];
    [topBar addSubview:labelTitle];
    [labelTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(labelTitle.superview);
    }];
    
    UIView *line = [UIView new];
    line.backgroundColor = [UIColor colorWithRed:160/255.0f green:160/255.0f blue:160/255.0f alpha:1.0f];
    [topBar addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(topBar);
        make.height.equalTo(@0.5f);
    }];
    
    self.infoTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    if (@available(iOS 11.0, *)) {
        self.infoTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.infoTableView.contentInset = UIEdgeInsetsZero;
    self.infoTableView.estimatedSectionFooterHeight = CGFLOAT_MIN;
    self.infoTableView.estimatedSectionHeaderHeight = CGFLOAT_MIN;
    self.infoTableView.sectionHeaderHeight = CGFLOAT_MIN;
    self.infoTableView.sectionFooterHeight = CGFLOAT_MIN;
    self.infoTableView.tableFooterView = [UIView new];
    self.infoTableView.tableHeaderView = [UIView new];
    [NewCellManager registerCellFor:self.infoTableView];
    self.infoTableView.dataSource = self;
    self.infoTableView.delegate = self;
    
    [self.view addSubview:self.infoTableView];
    [self.infoTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.infoTableView.superview);
        make.top.equalTo(topBar.mas_bottom);
    }];
    self.infoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refresh];
    }];
    [self.infoTableView.mj_header beginRefreshing];
}


#pragma mark 刷新
- (void)refresh {
    
    // 初始化
    self.pageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    if (self.infoTableView.mj_footer) {
        self.infoTableView.mj_footer = nil;
    }
    
    __weak typeof(self) weakSelf = self;
    
    // 开始请求
    self.requestHandle = [ServiceUserNew doGetMyComments:self.pageIndex pageSize:self.pageSize success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
        weakSelf.requestHandle = nil;
        [weakSelf.infoTableView.mj_header endRefreshing];
        weakSelf.news = [NSMutableArray arrayWithArray:responseObject];
        [weakSelf.infoTableView reloadData];
        
        // 判断是否有加载更多
        weakSelf.pageIndex += 1;
        if ([responseObject count] >= weakSelf.pageSize) {
            weakSelf.infoTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
                [weakSelf loadMore];
            }];
        }
        
    } failure:^(NSString * _Nonnull message) {
        weakSelf.requestHandle = nil;
        [weakSelf.infoTableView.mj_header endRefreshing];
        [weakSelf showHUDText:message];
    }];
    
}

#pragma mark 加载更多
- (void)loadMore {
    if (!self.requestHandle) {
        __weak typeof(self) weakSelf = self;
        
        // 开始请求
        self.requestHandle = [ServiceUserNew doGetMyComments:self.pageIndex pageSize:self.pageSize success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
            weakSelf.requestHandle = nil;
            [weakSelf.news addObjectsFromArray:responseObject];
            [weakSelf.infoTableView reloadData];
            
            // 判断是否有加载更多
            weakSelf.pageIndex += 1;
            if ([responseObject count] <= weakSelf.pageSize) {
                [weakSelf.infoTableView.mj_footer endRefreshing];
            } else {
                [weakSelf.infoTableView.mj_footer endRefreshingWithNoMoreData];
            }
            
        } failure:^(NSString * _Nonnull message) {
            weakSelf.requestHandle = nil;
            [weakSelf.infoTableView.mj_footer endRefreshing];
            [weakSelf showHUDText:message];
        }];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.news count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [NewCellManager cellForNews:self.news[indexPath.row] whos:0 tableView:tableView];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [NewCellManager heightForNewsCell:self.news[indexPath.row] whos:0];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    M_News *news_ = [self.news objectAtIndex:indexPath.row];
    [NewCellManager jumpToNewsDetail:news_ wohs:0 handle:self];
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

@end
